package com.itheima.reggie.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.reggie.common.R;
import com.itheima.reggie.dto.DishDto;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Dish;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.DishService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/setmeal")
@Slf4j
public class SetmealController {

    @Autowired
    private SetmealDishService setmealDishService;

    @Autowired
    private SetmealService setmealService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private DishService dishService;


    /**
     * 新增套餐
     * @param setmealDto
     * @return
     */
    @PostMapping
    @CacheEvict(value = "SetmealCache",allEntries = true)
    public R<String> save(@RequestBody SetmealDto setmealDto){
        log.info("新增套餐为：{}",setmealDto);
        setmealService.saveWiteDish(setmealDto);
        return R.success("新增成功");
    }

    /**
     * 分页查询
     * @param page
     * @param pageSize
     * @param name
     * @return
     */
    @GetMapping("/page")
    public R<Page<SetmealDto>> page(int page,int pageSize,String name){
        //构建分页查询构造器
        Page<Setmeal> pageInfo = new Page<>(page,pageSize);
        //构建条件查询器
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.like(name!= null,Setmeal::getName,name);
        wrapper.orderByDesc(Setmeal::getUpdateTime);
        //执行分页查询
        setmealService.page(pageInfo,wrapper);

        //套餐setmeal信息不包含 分类名称 ，所以使用setmealDto封装信息，
        // 将setmeal的信息复制到setmealDto，并且添加 分类名称 的信息, 且records的泛型是是setmeal
        Page<SetmealDto> setmealDtoPage = new Page<>();
        BeanUtils.copyProperties(pageInfo,setmealDtoPage,"records");

        //获取原始records
        List<Setmeal> records = pageInfo.getRecords();
        //遍历records
        List<SetmealDto> setmealDtos = records.stream().map((item) -> {
            //将setmeal的基本信息复制到setmealDto中
            SetmealDto setmealDto = new SetmealDto();
            BeanUtils.copyProperties(item, setmealDto);

            //根据id查找到分类名称，并添加到setmealDto中
            Long categoryId = item.getCategoryId();
            Category category = categoryService.getById(categoryId);

            if (category != null) {
                //获取到分类名称
                String categoryName = category.getName();
                //将分类名称添加到setmealDto
                setmealDto.setCategoryName(categoryName);
            }
            return setmealDto;
        }).collect(Collectors.toList());

        //设置新的records
        setmealDtoPage.setRecords(setmealDtos);
        return R.success(setmealDtoPage);
    }

    /**
     * 删除套餐
     * @param ids
     * @return
     */
    @DeleteMapping
    @CacheEvict(value = "SetmealCache",allEntries = true)
    public R<String> delete(@RequestParam List<Long> ids){
        log.info("要删除的id为：{}",ids);
        setmealService.removeWithDish(ids);
        return R.success("套餐删除成功");
    }

    @PostMapping("/status/{status}")
    @CacheEvict(value = "SetmealCache",allEntries = true)
    public R<String> status(@PathVariable int status,@RequestParam List<Long> ids){
        log.info("要修改的ids为{},状态修改为，{}",ids,status);
        //遍历每一个套餐，修改其状态
        for (Long id : ids) {
            //根据id查询到该套餐
            Setmeal setmeal = setmealService.getById(id);
            //修改状态
            setmeal.setStatus(status);
            //更新
            setmealService.updateById(setmeal);
        }
        return R.success("状态修改成功");
    }

    /**
     * 根据id查询套餐基本信息和菜品信息
     * @param ids
     * @return
     */
    @GetMapping("{ids}")
    public R<SetmealDto> getById(@PathVariable Long ids){
        log.info("要查询的id为：{}",ids);
        SetmealDto setmealDto = setmealService.getByIdWithDish(ids);
        return R.success(setmealDto);
    }

    /**
     * 修改套餐
     * @param setmealDto
     * @return
     */
    @PutMapping
    @CacheEvict(value = "SetmealCache",allEntries = true)
    public R<String> update(@RequestBody SetmealDto setmealDto){
        log.info("要修改的套餐信息为：{}",setmealDto);

        setmealService.updateWithDish(setmealDto);
        return R.success("修改成功");
    }

    /**
     * 查询套餐信息
     * @param categoryId
     * @param status
     * @return
     */
    @GetMapping("/list")
    @Cacheable(value = "SetmealCache",key = "#categoryId + '_' + #status")
    public R<List<Setmeal>> list(Long categoryId,String status){
        //根据前端传入的套餐id和状态查询
        LambdaQueryWrapper<Setmeal> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(categoryId != null,Setmeal::getCategoryId,categoryId);
        wrapper.eq(status != null,Setmeal::getStatus,status);

        List<Setmeal> list = setmealService.list(wrapper);

        return R.success(list);
    }

    @GetMapping("/dish/{id}")
    public R<List<DishDto>> getDish(@PathVariable Long id){
        log.info("展示的套餐id为：{}",id);

        LambdaQueryWrapper<SetmealDish> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(id != null,SetmealDish::getSetmealId,id);
        List<SetmealDish> list = setmealDishService.list(wrapper);

        List<DishDto> dishDtoList = list.stream().map((item) -> {
            DishDto dishDto = new DishDto();
            //其实这个BeanUtils的拷贝是浅拷贝，这里要注意一下
            BeanUtils.copyProperties(item, dishDto);
            //这里是为了把套餐中的菜品的基本信息填充到dto中，比如菜品描述，菜品图片等菜品的基本信息
            Long dishId = item.getDishId();
            Dish dish = dishService.getById(dishId);
            BeanUtils.copyProperties(dish, dishDto);
            return dishDto;
        }).collect(Collectors.toList());
        return R.success(dishDtoList);
    }
}
